/*
 * @ : Copyright (c) 2021 Phytium Information Technology, Inc. 
 *  
 * SPDX-License-Identifier: Apache-2.0.
 * 
 * @Date: 2021-09-06 15:32:14
 * @LastEditTime: 2021-09-06 15:38:03
 * @Description:  This files is for 
 * 
 * @Modify History: 
 *  Ver   Who        Date         Changes
 * ----- ------     --------    --------------------------------------
 */
#include <string.h>
#include <stdio.h>
#include "parameters.h"
#include "../src/shell.h"
#include "qspi.h"
#include "qspi_hw.h"

static QSpiCtrl ctrl;

static void NorFlashTestInit(QSpiCtrl *pCtrl, QSpiConfig *pConfig)
{
    u32 id = QSPI_INSTANCE;
    u32 ret = QSPI_SUCCESS;

    memset(pCtrl, 0, sizeof(QSpiCtrl));
    printf("start test\r\n");
    *pConfig = *NorFlashLookupConfig(id);
    ret = NorFlashInit(pCtrl, pConfig);
}

static void NorFlashReadID()
{
    QSpiCtrl *pCtrl = &ctrl;
    QSpiConfig *pConfig = &ctrl.config;
    u8 flashId[6] = {0};
    u32 ret = QSPI_SUCCESS;

    NorFlashTestInit(pCtrl, pConfig);

    ret = NorFlashReadReg(pCtrl, QSPI_FLASH_CMD_RDID, flashId, sizeof(flashId));

    if (QSPI_SUCCESS != ret)
    {
        printf("failed, test result 0x%x\r\n", ret);
    }

    printf("Manufacturer ID: 0x%x\r\n", flashId[0]);
    if ((0x02 == flashId[1]) && (0x19 == flashId[2]))
    {
        printf("Capcity: 256MB\r\n");
    }
    else if ((0x20 == flashId[1]) && (0x18 == flashId[2]))
    {
        printf("Capcity: 128MB\r\n");
    }
    else
    {
        printf("Capcity: Unkonwn\r\n");
    }

    if (0x00 == flashId[4])
    {
        printf("Sector: 256KB\r\n");
    }
    else if (0x01 == flashId[4])
    {
        printf("Sector: 64KB\r\n");
    }
    else
    {
        printf("Sector: Unkonwn\r\n");
    }

    printf("Family Id: 0x%x\r\n", flashId[5]);     
}

static void QspiUsage()
{
	printf("usage:\r\n");
	printf("    qspi -i\r\n");
}

static int QspiCmdEntry(int argc, char *argv[])
{
    char byte;
    int times;

    if(argc < 2)
	{
		QspiUsage();
        return -1;
	}

    if(!strcmp(argv[1], "-i"))
    {
        NorFlashReadID();
    }

    return 0;
}

SHELL_EXPORT_CMD(SHELL_CMD_TYPE(SHELL_TYPE_CMD_MAIN), qspi, QspiCmdEntry, test qspi nor flash driver);